# -*- coding: utf-8 -*-
from datetime import datetime

from django.shortcuts import redirect, reverse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings

from web import models


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    """使用中间件校验用户信息"""
    
    # 每次请求，都会先执行该方法
    def process_request(self, request):
        """用户已经登录"""
        
        request.tracer = Tracer()
        
        user_id = request.session.get('user_id')
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        
        request.tracer.user = user_obj
        
        # 白名单：可以访问url
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        
        # 路由限制
        if not request.tracer.user:
            return redirect(reverse('web:login'))
        
        # 登录成功后，访问项目管理时，回去用户的额度
        
        # 方式一：免费额度在交易记录中存储
        # 获取最近的记录
        _obj = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 判断套餐是否过期
        current_time = datetime.now()
        if _obj.end_time and _obj.end_time < current_time:
            # 过期后，重置会免费版本
            # _obj = models.Transaction.objects.filter(user=user_obj, status=2).order_by('id').first()
            _obj = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()
        request.tracer.price_policy = _obj.price_policy
        
        # 方式二：在配置文件中存储
        # _obj = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # if not _obj:
        #     # 没有买套餐
        #     request.tracer.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        #     print('没有买套餐:', request.tracer.price_policy)
        # else:
        #     # 买了付费版的
        #     current_time = datetime.now()
        #     if _obj.end_time and _obj.end_time < current_time:
        #         # 过期
        #         request.tracer.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        #         print('过期了：', request.tracer.price_policy)
        #     else:
        #         request.tracer.price_policy = _obj.price_policy
        #         print('没过期：', request.tracer.price_policy)
    
    def process_view(self, request, view, args, kwargs):
        
        # 判断是否未/manage/开头，是，则判断项目是否为自己创建的 或 创建的
        if not request.path_info.startswith('/manage/'):
            return
        
        project_id = kwargs.get('project_id')
        
        # 是否是我创建的
        obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        
        if obj:
            # 是自己创建的项目，则通过
            request.tracer.project = obj
            return
        
        # 是否是参与的项目
        obj = models.Participant.objects.filter(user=request.tracer.user, project_id=project_id).first()
        
        if obj:
            # 是自己参加项目，则通过
            request.tracer.project = obj.project
            return
        
        # 是已/manage/开头，但不是自己参加或参与的，则重定向
        return redirect(reverse('web:project_list'))
